package com.lzx.applib.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.TextView;

import com.lzx.applib.R;
import com.lzx.applib.listener.SimpleAnimatorListener;

/**
 * Created by Administrator on 16/12/11.
 */

public class ExpandTextView extends TextView {

    int expandTime = 1000;
    private int maxLines;
    private int minLines;
    private boolean expanding = false;

    public ExpandTextView(Context context) {
        this(context, null);
    }

    public ExpandTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ExpandTextView);
        expandTime = array.getInt(R.styleable.ExpandTextView_expandTime, expandTime);
        array.recycle();
        minLines = getMaxLines();
    }

    @Override
    public void setLines(int lines) {
        super.setLines(lines);
        this.maxLines = lines;
    }

    @Override
    public int getMaxLines() {
        return maxLines;
    }

    @Override
    public void setMaxLines(int maxlines) {
        super.setMaxLines(maxlines);
        this.maxLines = maxlines;
    }

    public void expand(int newLines) {
        if (expanding) return;
        expanding = true;

        setLines(newLines);
        measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
                MeasureSpec.makeMeasureSpec(((View)getParent()).getHeight(), MeasureSpec.AT_MOST));

        int fromHeight = getHeight();
        int toHeight = getMeasuredHeight();

        ValueAnimator animator = ValueAnimator.ofInt(fromHeight, toHeight);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int h = (int) animation.getAnimatedValue();
                setHeight(h);
            }
        });
        animator.setDuration(expandTime);
        animator.addListener(new SimpleAnimatorListener(){
            @Override
            public void onAnimationEnd(Animator animation) {
                expanding = false;
            }
        });
        animator.start();
    }

    public void change() {
        if (maxLines == getLineCount()) {
            expand(minLines);
        } else {
            expand(getLineCount());
        }
    }

    /**This should be call after layout*/
    public boolean canExpland() {
        int lineCount = getLineCount();
        return minLines < lineCount;
    }

    public boolean isExpanding() {
        return expanding;
    }
}
